<template>
  <a-button type="link" :size="size" @click="moveData()">添加一个{{ config.title }}</a-button>
  <a-button v-if="batchAddBtn" type="link" :size="size" @click="hideModal(true)">批量设置{{ config.title }}</a-button>
  <a-table :columns="config.columns" :dataSource="dataSource" bordered :size="size" :pagination="false">
    <template v-for="col in config.columns" #[col.dataIndex]="data" :key="col.dataIndex">
      <a-select
        v-if="col.inputType === 'select'"
        :size="size"
        style="width: 100%"
        :defaultValue="getCellValue(props, col.dataIndex, col.selectDefault)"
        @change="(val) => setCellValue(props, col.dataIndex, val)"
      >
        <template v-for="(key, value) in col.selectMap" :key="key">
          <a-select-option :value="key">{{ value }}</a-select-option>
        </template>
      </a-select>
      <a-col v-else :ref="(el) => setRef(el, data.value)">
        <a-input style="margin: -5px 0" :value="data.value" @change="(e) => handleChange(e.target.value, data.record, col.dataIndex)" :size="size" />
      </a-col>
    </template>
    <template #action="{ index }">
      <div class="editable-row-operations">
        <span>
          <a @click="moveData(index, -1)">上移</a>
          <a-divider type="vertical" />
          <a @click="moveData(index, 1)">下移</a>
          <a-divider type="vertical" />
          <a-popconfirm title="您确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="moveData(index, 0)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </div>
    </template>
  </a-table>
  <a-modal
    :visible="visibleModel"
    :title="'请输入' + config.title"
    ok-text="设置"
    cancel-text="关闭"
    @ok="hideModal(false)"
    @cancel="handleCancel(false)"
  >
    <div class="modal">
      <a-textarea
        v-model="modelValue"
        placeholder="一行一个，冒号(:)、等号（=）、空格或tab分割name和value"
        :auto-size="{ minRows: 8, maxRows: 20 }"
      />
    </div>
  </a-modal>
</template>
<script setup>
  import { onMounted, ref, nextTick } from 'vue';
  import { setCellValue, getCellValue } from '../utils/tools';
  const props = defineProps({
    config: { type: Object },
    cell: { type: Object },
    editor: { type: Object },
    direction: { type: String },
    batchAddBtn: {
      type: Boolean,
      // 对象或数组默认值必须从一个工厂函数获取
      default: function () {
        return true;
      },
    },
  });
  const emit = defineEmits(['tableData']);
  const visibleModel = ref(false);
  const modelValue = ref('');
  const dataSource = ref([]);
  const keyId = Math.random();
  const size = ref('small');
  const getRef = ref({});
  const setRef = (el, item) => {
    if (el) {
      getRef.value[item] = el;
      emit('tableData', getRef.value);
    }
  };
  onMounted(() => {
    nextTick(() => {
      initDataSource();
    });
  });
  function initDataSource() {
    const keys = props.config.keys;
    let paramsData = {};
    let length = 0;
    keys.forEach((element) => {
      paramsData[element] = getCellValue(props, element);
      length = paramsData[element] ? paramsData[element].length : 0;
    });
    for (let index = 0; index < length; index++) {
      let tempData = {
        key: keyId + index,
      };
      keys.forEach((key) => {
        if (paramsData[key] !== undefined) {
          tempData[key] = paramsData[key][index];
        }
      });
      dataSource.value.push(tempData);
    }
    emit('tableData', getRef.value);
  }
  // 列修改框修改值
  function handleChange(value, record, col) {
    record[col] = value;
    setAllDataToCell();
  }
  //设置所有参数
  function setAllDataToCell() {
    const keys = props.config.keys;
    // 初始化数组值
    let params = {};
    keys.forEach((element) => {
      params[element] = [];
    });
    // 放入值
    dataSource.value.forEach((element) => {
      for (let key in element) {
        if (key !== 'key') {
          params[key].push(element[key]);
        }
      }
    });
    // 写入值
    for (let key2 in params) {
      if (params[key2].length > 0) {
        setCellValue(props, key2, params[key2]);
      }
    }
  }
  // 全局参数修改值
  function moveData(index, oper) {
    switch (oper) {
      case -1:
        if (index > 0) {
          let temp = dataSource.value.splice(index, 1);
          dataSource.value.splice(index - 1, 0, temp[0]);
        }
        break;
      case 1:
        if (index < dataSource.value.length) {
          let temp = dataSource.value.splice(index, 1);
          dataSource.value.splice(index + 1, 0, temp[0]);
        }
        break;
      case 0:
        dataSource.value.splice(index, 1);
        break;
      default:
        const keys = props.config.keys;
        let paramsData = {
          key: keyId + dataSource.value.length,
        };
        keys.forEach((element) => {
          paramsData[element] = '';
        });
        dataSource.value.push(paramsData);
        break;
    }
  }
  function hideModal(show) {
    visibleModel.value = show;
    if (show === false) {
      let inputDatas = modelValue.value.split('\n');
      inputDatas.forEach((element) => {
        const splitChar = [':', '=', ' ', '\t'];
        for (const index in splitChar) {
          let inputIndex = element.indexOf(splitChar[index]);
          if (inputIndex !== -1) {
            let temp = {
              keys: keyId + dataSource.value.length,
            };
            temp[props.config.keyPrefix + '-name'] = element.substring(0, inputIndex);
            temp[props.config.keyPrefix + '-value'] = element.substring(inputIndex + 1);
            temp[props.config.keyPrefix + '-description'] = '';
            dataSource.value.push(temp);
            break;
          }
        }
      });
    }
    modelValue.value = '';
    setAllDataToCell();
  }
  function handleCancel(show) {
    visibleModel.value = show;
  }
</script>

<style lang="less" scoped>
  .modal {
    padding: 24px;
  }
  :deep(.ant-table-tbody) {
    .ant-table-measure-row {
      visibility: collapse !important;
    }
  }
</style>
